package com.totoro.rabbitmq.PTP;

import com.rabbitmq.client.*;
import com.totoro.rabbitmq.RabbitMQUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by Niki on 2018/3/28 8:27
 */
public class PTPClient {
    private static String queue_name = "hello_demo_queue";

    private static void receive() {
        ConnectionFactory connectionFactory = RabbitMQUtil.getConnectionFactory();
        Connection connection = null;
        Channel channel = null;
        try {
            connection = connectionFactory.newConnection();
            channel = connection.createChannel();

            //声明队列 queue_name 与服务端名称一致
            channel.queueDeclare(queue_name, false, true, true, null);

            channel.basicConsume(queue_name, true, new Consumer() {
                public void handleConsumeOk(String consumerTag) {

                }

                public void handleCancelOk(String consumerTag) {

                }

                public void handleCancel(String consumerTag) throws IOException {

                }

                public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {

                }

                public void handleRecoverOk(String consumerTag) {

                }

                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("PTP client receive msg :" + new String(body, "utf-8"));
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {
            RabbitMQUtil.closeChannel(channel);
            RabbitMQUtil.closeConnection(connection);
        }
    }
}
